package com.tlvip.io.client;

import com.tlvip.io.netty.server.TimeServerHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

/**
 * <p>文件描述：</p>
 * <p>版权所有： 版权所有(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>内容摘要： </p>
 * <p>其他说明： </p>
 * Date 2019-12-18</p>
 * Author mac
 *
 * @version 1.0
 */
public class TimeClientHandler extends ChannelHandlerAdapter {
    private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());

    private final ByteBuf firstMessage;

    public TimeClientHandler() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    // 客户端与服务端建立连接后，此方法就被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 向服务端发送查询时间的请求命令
        System.out.println("1.client call Time:" + System.currentTimeMillis());
        ctx.writeAndFlush(firstMessage);
    }

    // 服务端返回应答时，此方法被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = TimeServerHandler.handlerMsg(msg);
        System.out.println("3.client receive callBack time:" + System.currentTimeMillis());
        System.out.println("Now is :" + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warning("Unexpected exception from downstream:" + cause.getMessage());
        // close resource
        ctx.close();
    }
}
